package org.amphiprion.descentv2assistant.dao.xml;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class AbstractXmlDao {
	protected String getAttribute(Element node, String name, String defaultValue) {
		if (node == null) {
			return defaultValue;
		}
		String s = node.getAttribute(name);
		if (s == null || "".equals(s)) {
			return defaultValue;
		} else {
			return s;
		}
	}

	protected int getIntAttribute(Element node, String name, int defaultValue) {
		if (node == null) {
			return defaultValue;
		}
		String s = node.getAttribute(name);
		if (s == null || "".equals(s)) {
			return defaultValue;
		} else {
			try {
				return Integer.parseInt(s);
			} catch (Throwable e) {
				return defaultValue;
			}
		}
	}

	protected boolean getBooleanAttribute(Element node, String name, boolean defaultValue) {
		if (node == null) {
			return defaultValue;
		}
		String s = node.getAttribute(name);
		if (s == null || "".equals(s)) {
			return defaultValue;
		} else {
			if ("1".equals(s) || "true".equals(s)) {
				return true;
			} else {
				return false;
			}
		}
	}

	protected String getLocalizedText(Element node, String lng) {
		String name = "";
		NodeList langs = node.getElementsByTagName("lang");
		for (int iNames = 0; iNames < langs.getLength(); iNames++) {
			Element lang = (Element) langs.item(iNames);
			String local = getAttribute(lang, "id", "");
			if (local.equals(lng)) {
				if (lang.getFirstChild() == null) {
					name = "";
				} else {
					name = lang.getFirstChild().getNodeValue();
				}
				break;
			} else if ("en".equals(local)) {
				if (lang.getFirstChild() == null) {
					name = "";
				} else {
					name = lang.getFirstChild().getNodeValue();
				}
			}
		}
		return name;
	}
}
